#!/usr/bin/env python
import ast
import json
import pika
import pymongo
import sys
import dateutil.parser

from pymongo import MongoClient

MONGO_CONNECTION_STRING="mongodb://test:test@localhost:27017/smog"
MONGO_COLLECTION="measurements"

# connection to MongoDB
try:
    dbConnection = pymongo.MongoClient(MONGO_CONNECTION_STRING)
    print "Connected to MongoDB successfully."
except pymongo.errors.ConnectionFailure as e:
    print "Could not connect to MongoDB: %s" % e
    sys.exit(1)

db = dbConnection.smog
collection = db[MONGO_COLLECTION]

# connection to message queue
mqConnection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = mqConnection.channel()
channel.queue_declare(queue='sensor')

print ' [*] Waiting for messages. To exit press CTRL+C'

def callback(ch, method, properties, body):

    print " [x] Received %r" % (body,)

    # Convert the message payload to a python dictionary
    data_object = json.loads(body)
    
    # Replace the iso8601 time sting in the object by a datetime object
    data_object['time'] = dateutil.parser.parse(data_object['time'])

    # Insert the dictionary into the collection
    collection.insert(data_object)


channel.basic_consume(callback, queue='sensor', no_ack=True)
channel.start_consuming()
# TODO: handle ctrl-c event gracefully
 
